#include"MFO.h"

my_FILE* my_fopen(const char *filename, const char *mode){
	int fd;
	if(0==strcmp(mode,"w")){//选择选项
		fd=open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
	}
	else if(0==strcmp(mode,"r")){
		fd=open(filename,O_RDONLY);
	}
	else if(0==strcmp(mode,"a")){
		fd=open(filename,O_WRONLY | O_CREAT | O_APPEND,0666);
	}
	else return NULL;
	if(fd==-1) return NULL;

	my_FILE *filep=(my_FILE*)malloc(sizeof(my_FILE));//创建my_FILE
	if(filep==NULL) return NULL;
	
	filep->_fd=fd;//初始化
	filep->_flag=BY_ALL;
	filep->_size=0;
	filep->_cap=SIZE;
	
	return filep;
}


int my_fclose(my_FILE *stream){
	if(stream->_size > 0) my_fflush(stream);
	if(close(stream->_fd)) return EOF;
	else{
		free(stream);
		return 0;
	}
}

size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, my_FILE *stream){
	int i=1;
	size_t answer=0;
	while(i<=nmemb){
		if(stream->_size+size > stream->_cap) my_fflush(stream);
		
		memcpy(stream->_lib_buffer+stream->_size,(char*)ptr+(i-1)*size,size);
		stream->_size+=size;
		answer+=size;
		i++;
	}

	if(stream->_flag==BY_NOBUF || stream->_flag==BY_LINES && stream->_lib_buffer[stream->_size-1]=='\n'){
		my_fflush(stream);
	}
	return answer;
}

int my_fflush(my_FILE * stream){	
	int r=write(stream->_fd,stream->_lib_buffer,stream->_size);
	if(r!=stream->_size) return EOF;
	else return 0;
}
